package development.app;

import java.util.Vector;

import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.SMSHandler;
import state.SendSMSListener;
import state.component.Event;
import state.component.EventListener;
import state.component.GridMenu;
import state.font.FontManager;
import state.font.ImageText;
import state.socket.DataPackage;
import state.util.GameColor;
import state.util.Hashtable;
import state.util.array.ByteArray;
import state.util.array.StringArray;
import development.DrawUtils;
import development.Global;
import development.group.FrmGroupCuaHang18PlusNapXu;

public class FrmCuaHangMedia extends GameForm implements EventListener, SendSMSListener {
  public static String CUAHANG_NAME;
  public static String CUAHANG_CATEGORY_CODE;

  private ImageText text8;
  private ImageText textDownload;
  private int chooseIndex;
  private int pageIndex;
  private int HOZ_DISTANCE = 60;
  private int VER_DISTANCE = 55;
  private int DX = 30;
  private int DY = 165;
  private int NUMBER_OF_ITEM_PER_ROW = 4;
  private int numberOfItem;

  String[] listTypeDraw = new String[] { "drawCategory", "drawContentList", "drawContent" };
  String[] lthTypeDraw = new String[] { "drawList", "drawValue" };
  String type;
  String categorycode;
  String categoryname;
  private CuaHangCategory categorys;
  CuaHangContent appcontentmedias;
  CuaHangContent contentmedias;
  int MAXPAGE = 1;
  int totalcount;
  int MAXROW = 10;
  int countpercent;
  Vector categoryList;
  Vector contentList;
  String filename;
  String title;
  int downloadType;// 0 download, 1 sendgift
  int distanceY = 0;
  boolean isshowdetail;
  int ispaidok;
  boolean isDownloadCompleted;
  int notifyLength;
  private FrmSendGiftAlert frmSendGiftAlert;
  int mediaIndexSelected;
  private static GameForm singleton;
  String urldownload;
  byte[] destarray;
  byte[] buffer;
  private GridMenu gridMenu;
  boolean isOnRecieveData;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmCuaHangMedia();
    }
    return singleton;
  }

  public FrmCuaHangMedia() {
  }

  public void init(Hashtable hashtable) {

    isOnRecieveData = false;
    chooseIndex = 0;
    pageIndex = 0;
    totalcount = 0;

    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    textDownload = FontManager.getFont(FontManager.FONT_SIZE_8);

    type = listTypeDraw[0];
    countpercent = 0;
    categoryList = new Vector();
    contentList = new Vector();
    isshowdetail = false;
    categorycode = CUAHANG_CATEGORY_CODE;
    frmSendGiftAlert = new FrmSendGiftAlert();
    frmSendGiftAlert.setPosition(20, 20);
    frmSendGiftAlert.setSize(200, 200);
    buffer = new byte[1024];
    isDownloadCompleted = false;

    NUMBER_OF_ITEM_PER_ROW = 1;
    DY = 25;
    DX = 0;
    HOZ_DISTANCE = 0;
    VER_DISTANCE = 60;

    title = CUAHANG_NAME;
    _manager.enableTouchPad();
  }

  public void draw(Graphics g) {
    DrawUtils.drawAppBackground(g);
    _manager.enableTouchPad();
    if (type.equalsIgnoreCase(listTypeDraw[0]))
      drawCategory(g);
    else
      drawContentList(g);

    drawMenu(g);
  }

  private void drawMenu(Graphics g) {

    DrawUtils.drawTopBar(g);
    text8.drawString2(g, title, GameColor.WHITE_CODE, 10, 5, GameConstants.TOP_LEFT_ANCHOR);
    if (countpercent < 100) {
      DrawUtils.setBottomBar(_manager, "", countpercent + "%", "Trở về");
    } else {
      if (type.equalsIgnoreCase(listTypeDraw[1])) {
        DrawUtils.setBottomBar(_manager, "Gửi tặng", "Tải về", "Trở về");
        text8.drawString2(g, (pageIndex + 1) + "/" + MAXPAGE + " Trang", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 10, 5, GameConstants.TOP_RIGHT_ANCHOR);
      } else {
        DrawUtils.setBottomBar(_manager, "", "Chọn", "Trở về");
      }
    }
  }

  private void drawCategory(Graphics g) {
    DrawUtils.drawTopBar(g);
    if (isOnRecieveData) {
      if (!categoryList.isEmpty()) {
        for (int row = 0; row < numberOfItem; row++) {
          int x = DX + HOZ_DISTANCE * (row % NUMBER_OF_ITEM_PER_ROW);
          int y = DY + VER_DISTANCE * (row / NUMBER_OF_ITEM_PER_ROW);
          CuaHangCategory cates = (CuaHangCategory) categoryList.elementAt(row);
          if (chooseIndex == row) {
            g.setColor(0x4EA2D0);
            g.fillRect(0, y, GameConstants.SCREEN_WIDTH, VER_DISTANCE);
          }
          g.drawImage(cates.avatarimage, x + 24, y + 28, GameConstants.CENTER_ANCHOR); // avatar image
          text8.setBold(true);
          text8.drawString2(g, cates.name, GameColor.WHITE_CODE, x + 60, y + 1, GameConstants.TOP_LEFT_ANCHOR); // name
          text8.setBold(false);

          text8.drawParagraph1(g, "Mô tả :" + cates.subdescription, GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH - 50, -3, x + 60, y + 18); // description
          textDownload.drawString2(g, "Lượt tải: " + cates.downloadcount, GameColor.WHITE_CODE, x + 60, y + 45, GameConstants.TOP_LEFT_ANCHOR); // download count

          g.setColor(0xC0C0C0);
          g.drawLine(0, y + VER_DISTANCE, GameConstants.SCREEN_WIDTH, y + VER_DISTANCE);
        }
      } else {
        if (numberOfItem == 0) {
          countpercent = 100;
        }
      }
    }

  }

  private void drawContentList(Graphics g) {
    DrawUtils.drawTopBar(g);
    if (isOnRecieveData) {
      if (!contentList.isEmpty()) {
        for (int row = 0; row < numberOfItem; row++) {
          int x = DX + HOZ_DISTANCE * (row % NUMBER_OF_ITEM_PER_ROW);
          int y = DY + VER_DISTANCE * (row / NUMBER_OF_ITEM_PER_ROW);
          appcontentmedias = (CuaHangContent) contentList.elementAt(row);
          if (chooseIndex == row) {
            g.setColor(0x4EA2D0);
            g.fillRect(0, y, GameConstants.SCREEN_WIDTH, VER_DISTANCE);
          }
          g.drawImage(appcontentmedias.avatarimage, x + 24, y + 28, GameConstants.CENTER_ANCHOR); // avatar image
          text8.setBold(true);
          text8.drawString2(g, appcontentmedias.name, GameColor.WHITE_CODE, x + 60, y + 1, GameConstants.TOP_LEFT_ANCHOR); // name
          text8.setBold(false);

          text8.drawParagraph1(g, "Mô tả :" + appcontentmedias.description, GameColor.YELLOW_CODE, GameConstants.SCREEN_WIDTH - 50, -3, x + 60, y + 18); // description
          textDownload.drawString2(g, "Lượt tải: " + appcontentmedias.downloadcount, GameColor.WHITE_CODE, x + 60, y + 45, GameConstants.TOP_LEFT_ANCHOR); // download count

          g.setColor(0xC0C0C0);
          g.drawLine(0, y + VER_DISTANCE, GameConstants.SCREEN_WIDTH, y + VER_DISTANCE);
          g.setColor(0xC0C0C0);
          g.drawLine(0, y + VER_DISTANCE, GameConstants.SCREEN_WIDTH, y + VER_DISTANCE);
        }
      } else {
        if (numberOfItem == 0) {
          countpercent = 100;
        }
      }
    }
  }

  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.LEFT:
      pageIndex = (pageIndex - 1 < 0) ? 0 : pageIndex - 1;
      changePage(pageIndex);
      chooseIndex = 0;
      break;
    case Key.RIGHT:
      pageIndex = (pageIndex + 1 > MAXPAGE - 1) ? pageIndex : pageIndex + 1;
      changePage(pageIndex);
      chooseIndex = 0;
      break;
    case Key.DOWN:
      chooseIndex = (chooseIndex + NUMBER_OF_ITEM_PER_ROW > numberOfItem - 1) ? chooseIndex : chooseIndex + NUMBER_OF_ITEM_PER_ROW;
      int down;
      if (type.equalsIgnoreCase(listTypeDraw[2])) {
        DY -= VER_DISTANCE;
      } else {
        down = DY + VER_DISTANCE * (chooseIndex / NUMBER_OF_ITEM_PER_ROW);
        if (down > GameConstants.SCREEN_HEIGHT - VER_DISTANCE - 25)
          DY -= VER_DISTANCE;
      }
      break;
    case Key.UP:
      chooseIndex = (chooseIndex - NUMBER_OF_ITEM_PER_ROW < 0) ? chooseIndex : chooseIndex - NUMBER_OF_ITEM_PER_ROW;

      if (type.equalsIgnoreCase(listTypeDraw[2])) {
        DY += VER_DISTANCE;
      } else {
        int up = DY + VER_DISTANCE * chooseIndex;
        if (up < 25)
          DY += VER_DISTANCE;
      }
      break;
    case Key.ENTER:
      if (type.equalsIgnoreCase(listTypeDraw[0])) {
        categorys = (CuaHangCategory) categoryList.elementAt(chooseIndex);
        // truong hop ung dung,nhac chuong
        if (categorys.hasChild.equalsIgnoreCase("0")) { // show contentlist
          DataPackage contentdataPackage = DataPackage.createDataPackage1(FrmCuaHang.GET_CONTENT_LIST_REQUEST);
          contentdataPackage.putString(categorys.code);
          contentdataPackage.putInt(0);
          contentdataPackage.putInt(MAXROW);
          Global.appClient.write(contentdataPackage);
          numberOfItem = 0;
          type = listTypeDraw[1];
          contentList = new Vector();
          Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Ðang tải...", 99).setAlertTimeOut(5000);
        } else { // neu co child thi tiep tuc goi category
          DataPackage dataPackage = DataPackage.createDataPackage1(FrmCuaHang.GET_CATEGORY_LIST_REQUEST);
          dataPackage.putString(categorys.code);
          dataPackage.putInt(0);
          dataPackage.putInt(10);
          Global.appClient.write(dataPackage);
          numberOfItem = 0;
          categoryList = new Vector();
        }
        title = categorys.name;
        countpercent = 0;
        chooseIndex = 0;
        pageIndex = 0;

      } else if (type.equalsIgnoreCase(listTypeDraw[1])) {
        contentmedias = (CuaHangContent) contentList.elementAt(chooseIndex);
        Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create2( "Tải về bạn sẽ ", "phải thoát ứng dụng ", "Bạn có đồng ý không?" ), 55);
      }
      break;
    case Key.SOFT_RIGHT:
      back();
      break;
    case Key.SOFT_LEFT:
      if (type.equalsIgnoreCase(listTypeDraw[1])) {
        contentmedias = (CuaHangContent) contentList.elementAt(chooseIndex);
        GameGlobal.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create2( "Bạn có chắc", "gửi " + contentmedias.name, " cho bạn bè không" ), 56);
        break;
      }
    }
  }

  private void back() {
    if (categoryList == null || categoryList.size() == 0) {
      GameGlobal.nextState(FrmGroupCuaHang18PlusNapXu.instance(), null);
      return;
    }

    if (type.equalsIgnoreCase(listTypeDraw[0])) {
      categorys = (CuaHangCategory) categoryList.elementAt(chooseIndex);
      if (categorys == null) {
        GameGlobal.nextState(FrmGroupCuaHang18PlusNapXu.instance(), null);
      } else {
        if (categorycode.equalsIgnoreCase(categorys.parentCode))
          GameGlobal.nextState(FrmGroupCuaHang18PlusNapXu.instance(), null);
        else {
          DataPackage dataPackage = DataPackage.createDataPackage1(FrmCuaHang.GET_CATEGORY_PARENT_LIST_REQUEST);
          dataPackage.putString(categorys.parentCode);
          dataPackage.putInt(0);
          dataPackage.putInt(10);
          Global.appClient.write(dataPackage);
          numberOfItem = 0;
          categoryList = new Vector();
        }
      }
    } else if (type.equalsIgnoreCase(listTypeDraw[1])) {

      numberOfItem = categoryList.size();
      type = listTypeDraw[0];
      contentList = new Vector();
      chooseIndex = 0;
      DY = 25;
      DX = 0;
    }
  }

  private void changePage(int page) {
    if (type.equalsIgnoreCase(listTypeDraw[0])) {
      categorys = (CuaHangCategory) categoryList.elementAt(chooseIndex);
      DataPackage dataPackage = DataPackage.createDataPackage1(FrmCuaHang.GET_CATEGORY_LIST_REQUEST);
      dataPackage.putString(categorys.parentCode);
      dataPackage.putInt(page);
      dataPackage.putInt(MAXROW);
      Global.appClient.write(dataPackage);
      isOnRecieveData = false;
      categoryList = new Vector();
      Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);

    }
    if (type.equalsIgnoreCase(listTypeDraw[1])) {

      DataPackage contentdataPackage = DataPackage.createDataPackage1(FrmCuaHang.GET_CONTENT_LIST_REQUEST);
      contentdataPackage.putString(categorys.code);
      contentdataPackage.putInt(page);
      contentdataPackage.putInt(MAXROW);
      Global.appClient.write(contentdataPackage);
      isOnRecieveData = false;
      contentList = new Vector();
      Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(5000);
    }
    numberOfItem = 0;
  }

  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    GameGlobal.systemCanvas.hideAlert();
    switch (header) {
    case FrmCuaHang.GET_COUNT_RESPONSE:
      totalcount = dataPackage.nextInt();
      MAXPAGE = (int) Math.ceil((float) totalcount / (float) MAXROW);
      break;
    case FrmCuaHang.GET_CATEGORY_LIST_RESPONSE:
      isOnRecieveData = true;
      CuaHangCategory category = new CuaHangCategory();
      category.id = dataPackage.nextString();
      category.code = dataPackage.nextString();
      category.name = dataPackage.nextString();
      category.description = dataPackage.nextString();
      category.fee = dataPackage.nextString();
      category.parentCode = dataPackage.nextString();
      category.parentName = dataPackage.nextString();
      category.hasChild = dataPackage.nextString();
      category.downloadcount = dataPackage.nextString();
      ByteArray avi = dataPackage.nextByteArray();
      category.avatarimage = GameImage.createImage(avi, 0, avi.len());
      countpercent = dataPackage.nextInt();
      if (category.description.length() > 28)
        category.subdescription = category.description.substring(0, 28) + "...";
      else
        category.subdescription = category.description;
      categoryList.addElement(category);
      numberOfItem = categoryList.size();
      if (countpercent == 100)
        GameGlobal.systemCanvas.hideAlert();
      break;
    case FrmCuaHang.GET_CATEGORY_PARENT_LIST_RESPONSE:
      isOnRecieveData = true;
      CuaHangCategory objcate = new CuaHangCategory();
      objcate.id = dataPackage.nextString();
      objcate.code = dataPackage.nextString();
      objcate.name = dataPackage.nextString();
      objcate.description = dataPackage.nextString();
      objcate.fee = dataPackage.nextString();
      objcate.parentCode = dataPackage.nextString();
      objcate.parentName = dataPackage.nextString();
      objcate.hasChild = dataPackage.nextString();
      objcate.downloadcount = dataPackage.nextString();
      ByteArray objavi = dataPackage.nextByteArray();
      objcate.avatarimage = GameImage.createImage(objavi, 0, objavi.len());
      countpercent = dataPackage.nextInt();
      if (objcate.description.length() > 28)
        objcate.subdescription = objcate.description.substring(0, 28) + "...";
      else
        objcate.subdescription = objcate.description;
      categoryList.addElement(objcate);
      numberOfItem = categoryList.size();
      if (countpercent == 100)
        GameGlobal.systemCanvas.hideAlert();
      break;
    case FrmCuaHang.GET_CONTENT_LIST_RESPONSE:
      CuaHangContent appmedias = new CuaHangContent();
      appmedias.code = dataPackage.nextString();// code

      appmedias.name = dataPackage.nextString();// name
      appmedias.detail = dataPackage.nextString();// detail
      appmedias.money = dataPackage.nextString();// money
      appmedias.downloadcount = dataPackage.nextString();// downloadcount
      appmedias.data = dataPackage.nextString();// data
      ByteArray byteAvatarImage = dataPackage.nextByteArray();
      appmedias.avatarimage = GameImage.createImage(byteAvatarImage, 0, byteAvatarImage.len());
      countpercent = dataPackage.nextInt();
      if (appmedias.detail.length() > 28)
        appmedias.description = appmedias.detail.substring(0, 28) + "...";
      else
        appmedias.description = appmedias.detail;
      contentList.addElement(appmedias);
      numberOfItem = contentList.size();
      isOnRecieveData = true;

      break;
    }
  }

  public void destroy() {
    text8 = null;
    categoryList = null;
    contentList = null;
    pageIndex = 0;
    frmSendGiftAlert.destroy();
  }

  public void onActionPerform(Event event) {
    if (event.getSource() == gridMenu) {
      keyReleased(Key.FIRE);
    }
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == 55 && eventType == GameAlert.YES_BUTTON) { // download
      urldownload = null;
      urldownload = doDownloadWithHTTP(contentmedias.code);
      Global.systemCanvas.getMidlet().platformRequest(urldownload);
    }
    if (alertId == 56 && eventType == GameAlert.YES_BUTTON) {
      urldownload = null;
      urldownload = doDownloadWithHTTP(contentmedias.code);
      GameGlobal.alert.showCustomUIAlert(frmSendGiftAlert, 101);
    }

    if (alertId == 101) { // send gift
      String callNumber = frmSendGiftAlert.dest;
      String messageText = urldownload;
      int eventtype = frmSendGiftAlert.eventtype;
      if (eventtype == 1) {
        SMSHandler.getInstance(this).sendMsg(callNumber, messageText);
      }
    }
  }

  public void onSendSMSFail() {
    Global.alert.showAlert(this, GameAlert.OK_TYPE, "Gửi tin nhắn thất bại");
  }

  public void onSendSMSSuccess() {
    Global.alert.showAlert(this, GameAlert.OK_TYPE, "Gửi tin nhắn thành công");
  }

  public String doDownloadWithHTTP(String categoryId) {
    String Url = "http://winplay.vn/wap";
    if (CUAHANG_CATEGORY_CODE.equalsIgnoreCase("GAME")) {
      Url = "http://winplay.vn/wap/gameoff-detail.jsp?act=dv&page=1&catid=" + categorys.id + "&id=" + categoryId;
    } else if (CUAHANG_CATEGORY_CODE.equalsIgnoreCase("UNG_DUNG")) {
      Url = "http://winplay.vn/wap/app-detail.jsp?act=dv&page=1&catid=" + categorys.id + "&id=" + categoryId;
    } else if (CUAHANG_CATEGORY_CODE.equalsIgnoreCase("RING_BACK")) {
      Url = "http://winplay.vn/wap/ringback-detail.jsp?act=dv&page=1&catid=" + categorys.id + "&id=" + categoryId;
    } else if (CUAHANG_CATEGORY_CODE.equalsIgnoreCase("THEMES")) {
      Url = "http://winplay.vn/wap/theme-detail.jsp?act=dv&page=1&catid=" + categorys.id + "&id=" + categoryId;
    }
    return Url;
  }

  private class CuaHangCategory {
    String id;
    String code;
    String name;
    String description;
    String fee;
    String parentCode;
    String parentName;
    String hasChild;
    String downloadcount;
    GameImage avatarimage;
    String subdescription;
  }

  private class CuaHangContent {
    String code;
    String name;
    String detail;
    String money;
    String downloadcount;
    String data;
    GameImage avatarimage;
    String description;
  }
}